package demo04_route;

import com.rabbitmq.client.*;
import utils.ConnectionUtil;
import utils.LogLevelEnum;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

/**
 * @Description info 级别的消息消费者
 * @Author shihan
 * @Date 2020/12/20 21:54
 * @Version 1.0
 */
public class RInfoConsumer {

    public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(ConnectionUtil.URI);

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        // 声明 Exchange
        channel.exchangeDeclare(RProducer.EXCHANGE_NAME_DIRECT_ROUTE, BuiltinExchangeType.DIRECT);
        // 声明临时队列，并设置所有级别的 Binding key，让这个临时队列可以接收到所有级别的日志信息
        // 1、声明临时队列，并拿到临时队列的名称
        String queueName = channel.queueDeclare().getQueue();
        // 2、给队列设置 Binding key
        channel.queueBind(queueName,RProducer.EXCHANGE_NAME_DIRECT_ROUTE, LogLevelEnum.INFO.getDesc());

        // 监听消息队列，进行消息消费
        channel.basicConsume(queueName, true, new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                System.out.println("info级别日志的监听队列：" + new String(message.getBody(),"utf-8"));
            }
        }, new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
                // do nothing!
            }
        });

        // 此处不关闭连接，让 Connection 和 Channel 的连接均保持连通状态，方便监听队列接收消息！
    }

}
